package com.example.demo.configuration;

import com.example.demo.entity.Result;
import com.example.demo.entity.exception.EnumException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @description:
 * @author: cj
 * @create: 17-12-21 17:34:46
 */

@ControllerAdvice
@RestController
public class ExceptionConfig {
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.error( e.getMessage() );
    }

    @ExceptionHandler(EnumException.class)
    public Result enumException(EnumException e) {
        e.printStackTrace();
        String msg = e.enumResult.getMsg();
        Integer code = e.enumResult.getCode();
        return Result.error(msg ,  code);
    }

    /**
     * 1、"/hello0"配置了权限，会走最后的FilterSecurityInterceptor过滤器，而它的上一级ExceptionTranslationFilter则会处理AuthenticationException和AccessDeniedException，分别调用AuthenticationEntryPoint或AccessDeniedHandler
     * <br/>
     * 2、@PreAuthorize其实产生的是MethodSecurityInterceptor，就是一个method级别的AOP，spring异常处理有个"就近原则"，@ExceptionHandler则起了作用，如果取消掉，ExceptionTranslationFilter就会生效，也就意味着会走配置的AuthenticationEntryPoint或AccessDeniedHandler
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result accessDeniedException(AccessDeniedException e) {
        Result result = new Result();
        result.setStatus( 2213 );
        result.setMessage( "权限不足" );
        return result;
    }
    @ExceptionHandler(AuthenticationException.class)
    public Result accessDeniedException(AuthenticationException e) {
        Result result = new Result();
        result.setStatus( 500 );
        result.setMessage( e.getMessage () );
        return result;
    }
    @ExceptionHandler(BadCredentialsException.class)
    public Result accessDeniedException(BadCredentialsException e) {
        Result result = new Result();
        result.setStatus( 500 );
        result.setMessage( e.getMessage () );
        return result;
    }
}
